# -*- coding: utf-8 -*-

"""
调试商品页面的价格和评分元素定位
"""

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
import time
import re

def test_product_page():
    """
    测试商品页面元素定位
    """
    print("开始测试商品页面元素定位...")
    
    try:
        # 配置Chrome选项
        chrome_options = Options()
        chrome_options.add_argument("--headless")  # 无头模式
        chrome_options.add_argument("--no-sandbox")
        chrome_options.add_argument("--disable-dev-shm-usage")
        chrome_options.add_argument("--disable-gpu")
        chrome_options.add_argument("--window-size=1920,1080")
        chrome_options.add_argument("user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36")
        
        # 指定chromedriver路径
        service = Service("/usr/bin/chromedriver")
        
        # 创建WebDriver实例
        print("正在初始化WebDriver...")
        driver = webdriver.Chrome(service=service, options=chrome_options)
        
        # 访问一个商品页面进行测试
        test_url = "https://www.amazon.com/Stanley-Quencher-Flowstate-Tumbler-Stainless/dp/B0DR9PNXX3"
        print(f"正在访问商品页面: {test_url}")
        driver.get(test_url)
        time.sleep(5)  # 等待页面加载
        
        # 检查页面标题
        print(f"页面标题: {driver.title}")
        
        # 尝试定位价格元素
        print("\n=== 价格元素测试 ===")
        price_selectors = [
            ".a-price .a-offscreen",
            "#priceblock_dealprice",
            "#priceblock_ourprice",
            ".a-price-whole",
            ".a-price",
            "[data-a-strike='true'] .a-offscreen",
            ".a-row.a-spacing-mini .a-size-medium.a-color-price",
        ]
        
        for selector in price_selectors:
            try:
                elements = driver.find_elements(By.CSS_SELECTOR, selector)
                print(f"选择器 '{selector}': 找到 {len(elements)} 个元素")
                for i, element in enumerate(elements):
                    text = element.text.strip()
                    attr_value = element.get_attribute("innerHTML")
                    print(f"  元素 {i+1}: 文本='{text}', innerHTML='{attr_value[:100]}...'") 
            except Exception as e:
                print(f"选择器 '{selector}' 出错: {e}")
        
        # 尝试定位评分元素
        print("\n=== 评分元素测试 ===")
        rating_selectors = [
            ".a-icon-alt",
            "#acrPopover",
            ".a-popover-trigger .a-size-base",
            ".AverageCustomerReviews .a-size-medium",
            "[data-hook='rating-out-of-text']",
        ]
        
        for selector in rating_selectors:
            try:
                elements = driver.find_elements(By.CSS_SELECTOR, selector)
                print(f"选择器 '{selector}': 找到 {len(elements)} 个元素")
                for i, element in enumerate(elements):
                    text = element.text.strip()
                    attr_value = element.get_attribute("innerHTML")
                    print(f"  元素 {i+1}: 文本='{text}', innerHTML='{attr_value[:100]}...'") 
                    
                    # 尝试提取评分数字
                    if text:
                        rating_match = re.search(r'(\d+\.?\d*) out of 5 stars?', text)
                        if rating_match:
                            print(f"    提取评分: {rating_match.group(1)}")
            except Exception as e:
                print(f"选择器 '{selector}' 出错: {e}")
        
        # 尝试定位评分数元素
        print("\n=== 评分数元素测试 ===")
        review_count_selectors = [
            "#acrCustomerReviewText",
            ".a-size-base.a-link-normal",
            "[data-hook='total-review-count']",
            ".AverageCustomerReviews .a-size-small",
        ]
        
        for selector in review_count_selectors:
            try:
                elements = driver.find_elements(By.CSS_SELECTOR, selector)
                print(f"选择器 '{selector}': 找到 {len(elements)} 个元素")
                for i, element in enumerate(elements):
                    text = element.text.strip()
                    attr_value = element.get_attribute("innerHTML")
                    print(f"  元素 {i+1}: 文本='{text}', innerHTML='{attr_value[:100]}...'") 
                    
                    # 尝试提取评分数
                    if text:
                        review_count = re.sub(r'[^\d]', '', text)
                        if review_count:
                            print(f"    提取评分数: {review_count}")
            except Exception as e:
                print(f"选择器 '{selector}' 出错: {e}")
        
        # 关闭浏览器
        driver.quit()
        print("\n测试完成!")
        
    except Exception as e:
        print(f"测试过程中出现错误: {e}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    test_product_page()